﻿using System;
using System.Collections.Generic;
using System.Linq;
using EmitMapper;

namespace ObjectMapper.Benchmark
{
    public class EmitMapperExecutor : IMapExecutor
    {
        private readonly Dictionary<Tuple<Type, Type>, object> _mappers =
            new Dictionary<Tuple<Type, Type>, object>();

        public string Name
        {
            get
            {
                return "EmitMapper";
            }
        }

        public void Initialize()
        {
        }

        public void PreExecute<TSource, TTarget>()
        {
            var key = Tuple.Create(typeof(TSource), typeof(TTarget));
            if (!_mappers.ContainsKey(key))
            {
                var mapper = ObjectMapperManager.DefaultInstance.GetMapper<TSource, TTarget>();
                _mappers.Add(key, mapper);
                mapper.Map(Activator.CreateInstance<TSource>());
            }
        }

        public TTarget[] Execute<TSource, TTarget>(TSource[] entities)
        {
            var mapper = (ObjectsMapper<TSource, TTarget>) _mappers[Tuple.Create(typeof (TSource), typeof (TTarget))];
            return entities == null ? null : entities.Select(mapper.Map).ToArray();
        }

        public void PostExecute<TSource, TTarget>()
        {
        }
    }
}
